package com.ht.api.call.func.impl.official;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.open.OpenUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 修改公众号客服账号
 * @author asq
 * @createTime 2025年3月9日 09:11:00
 */
@Slf4j
@Deprecated
public class OfficialKfAccountEditFunctionCall implements IFunctionCall {
	/** 接口ID：修改公众号客服账号 */
	private static final long API_ID = 1909503363909816320L;
	/** 接口ID：设置公众号客服账号的头像 */
	private static final long API_ID_AVATAR = 1909903144515670016L;

	@Override
	public String getName() {
		return "修改公众号客服账号";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		String paramMainId = param.getStr("main_id");
		String nickname = param.getStr("nickname");
		String ossUrl = param.getStr("avatar");
		
		// 查询修改前的客服账号
		Entity oldKfAccount = Db.createSqlParser("wx_official_kf_account").findById(me.getDataSource(), paramMainId);
		if (oldKfAccount == null) {
			throw new HtException("客服账号不存在：" + paramMainId);
		}
		String appId = oldKfAccount.getStr("appid");
		String kfAccount = oldKfAccount.getStr("kf_account");
		
		// 请求平台接口修改昵称
		if (StrUtil.isNotBlank(nickname) && !oldKfAccount.getStr("nickname").equals(nickname)) {
			JSONObject accountParam = JSONUtil.createObj();
			accountParam.set("kf_account", kfAccount);
			accountParam.set("nickname", nickname);
			String str = OpenUtil.call(appId, API_ID, accountParam);
			JSONObject obj = JSONUtil.parseObj(str);
			if (obj.getInt("errcode") != 0) {
				throw new HtException("修改客服昵称失败：" + obj.getStr("errmsg"));
			}
		}
		
		// 请求平台接口修改头像
		if (StrUtil.isNotBlank(ossUrl) && !oldKfAccount.getStr("avatar").equals(ossUrl)) {
			JSONObject avatarParam = JSONUtil.createObj();
			avatarParam.set("kf_account", kfAccount);
			avatarParam.set("oss_url", ossUrl);
			String str = OpenUtil.call(appId, API_ID_AVATAR, avatarParam);
			JSONObject obj = JSONUtil.parseObj(str);
			if (obj.getInt("errcode") != 0) {
				log.warn("修改客服头像失败:{}", obj.getStr("errmsg"));
			}
		}
		
		return JSONUtil.createObj();
	}


}
